<template>
    <el-dialog :title="titleMap[mode]" v-model="visible" destroy-on-close @closed="$emit('closed')" :close-on-click-modal="false" :close-on-press-escape="mode != 'show' ? false : true" fullscreen>
        <el-form :model="form" :rules="rules" :disabled="mode=='show'" label-width="130" ref="dialogForm" style="height: calc(100vh - 100px);overflow-y: auto;">
            <el-row :gutter="1">
                <el-col :span="6">
                    <el-form-item label="退货日期" prop="ware_date">
						<el-date-picker v-model="form.ware_date" type="date" placeholder="请选择日期" :value-format="'YYYY-MM-DD'" style="width:100%"/>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="品名" prop="goods_id">
						<el-input v-model="form.goods_name" placeholder="品名" readonly @click="checkGoods(1)"></el-input>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12">
                    <el-form-item label="备注" prop="remark">
						<el-input v-model="form.remark" placeholder="备注" clearable></el-input>
					</el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="1">
                <el-col :xs="24" :sm="6">
                    <el-form-item label="供应商" prop="apply_id" style="align-items: center;">
                        <el-input v-model="form.remark" placeholder="" clearable>
                            <template #append>元</template>
                        </el-input>
						<el-select v-model="form.apply_id" placeholder="请选择" filterable>
							<el-option v-for="item in applyList" :key="item.apply_id" :label="item.apply_name" :value="item.apply_id"></el-option>
						</el-select>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="染色厂" prop="dye_factory" style="align-items: center;">
                        <el-input v-model="form.remark" placeholder="" clearable>
                            <template #append>元</template>
                        </el-input>
						<el-select v-model="form.dye_factory" placeholder="请选择" filterable>
							<el-option v-for="item in dyeList" :key="item.apply_id" :label="item.apply_name" :value="item.apply_id"></el-option>
						</el-select>
					</el-form-item>
                </el-col>
                <el-col :xs="24" :sm="6">
                    <el-form-item label="加工厂" prop="process_factory" style="align-items: center;">
                        <el-input v-model="form.remark" placeholder="" clearable>
                            <template #append>元</template>
                        </el-input>
						<el-select v-model="form.process_factory" placeholder="请选择" filterable>
							<el-option v-for="item in processList" :key="item.apply_id" :label="item.apply_name" :value="item.apply_id"></el-option>
						</el-select>
					</el-form-item>
                </el-col>
            </el-row>

            <!-- 入库单 -->
            <el-form-item>
                <el-link type="primary" style="margin-right: 20px" :underline="false" @click="checkArrival">入库单选择</el-link>
                <el-tag v-for="(item,index) in houseList" :key="index" :closable="mode != 'show'" type="info" style="margin-right: 20px" @close="delHouse(index)">
                    {{ item.code }}
                </el-tag>
            </el-form-item>
            <!-- 样本选择 -->
            <el-form-item>
                <el-link type="primary" style="margin-right: 20px" :underline="false" @click="checkSample">样本选择</el-link>
                <el-checkbox v-if="sampleList.length > 0" v-model="select_all" size="large" label="全选" @change="changeAll(select_all)" />
                <div style="margin-left: 20px;">
                    <el-checkbox v-for="(item,index) in sampleList" :key="index" v-model="item.show" size="large" :label="item.name" @change="sampleChange(item)" />
                </div>
            </el-form-item>
            
            <!-- 花型选择 -->
            <el-form-item>
                <el-link type="primary" style="margin-right: 20px" :underline="false" @click="checkFlower">花型选择</el-link>
                <el-tag v-for="(item,index) in flowerList" :key="index" :closable="mode != 'show'" type="info" style="margin-right: 20px" @close="delTag(index)">
                    {{ item.flower }}
                </el-tag>
            </el-form-item>

            <sc-form-table class="formtable" ref="table" v-model="form.order_detail" hideAdd hideDelete placeholder="暂无数据" show-summary :summary-method="handleSummary" :objectSpanMethod="objectSpanMethod" :cellStyle="cellStyle">
                <el-table-column label="花型" align="center" prop="flower">
                    <template #default="scope">
                        {{scope.row.flower}}
                    </template>
                </el-table-column>
                <el-table-column v-for="(item,index) in table_list" :key="index" :label="item.name" :prop="item.name" align="center">
                    <template #default="scope">
                        <el-input v-model="scope.row[item.name]" type="number" readonly class="inputDeep"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="合计" align="center" prop="total_number"></el-table-column>
                <el-table-column label="备注" align="center" width="200">
                    <template #default="scope">
                        <el-input v-model="scope.row.remark" @mousewheel.prevent placeholder="备注" clearable></el-input>
                    </template>
                </el-table-column>
            </sc-form-table>
        </el-form>
        <el-footer style="text-align: right;position: fixed;bottom: 0;right: 0;left: 0;padding: 10px 20px;background: #fff;border-top: 1px solid #eee;">
			<el-button @click="visible = false">取 消</el-button>
			<el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit(0)">保存</el-button>
		</el-footer>
    </el-dialog>
    <select-goods v-if="dialog.goods" ref="goodsDialog" @success="goodsBack" @closed="dialog.goods = false" :query="{is_show: 1}"></select-goods>
    <select-house v-if="dialog.house" ref="houseDialog" @success="houseBack" @closed="dialog.house = false" :query="{goods_id: form.goods_id, status: 1, can_use: 1}"></select-house><!-- 入库单选择 -->
    <select-flower v-if="dialog.flower" ref="flowerDialog" @success="flowerBack" @closed="dialog.flower = false" :query="{goods_id: form.goods_id,}"></select-flower><!-- 花型选择 -->
    <select-sample v-if="dialog.sample" ref="sampleDialog" @success="sampleBack" @closed="dialog.sample = false" :query="{goods_id: form.goods_id,}"></select-sample><!-- 样本选择 -->
</template>

<script>
import selectGoods from '@/views/basic/goods/selectGoods.vue';
import SelectHouse from '../../selectHouse.vue';
import SelectFlower from '../../selectFlower.vue';
import SelectSample from '../../selectSample.vue';
export default {
    emits: ['success', 'closed'],
    components: { selectGoods, SelectHouse, SelectFlower, SelectSample},
    data() {
        return {
            mode: "add",
            titleMap: {
                add: '新增调拨单',
                edit: '编辑调拨单',
                show: '查看调拨单',
            },
            visible: false,
            isSaveing: false,
            dialog: {
                goods: false,
            },
            form: {
                id: "",
                goods_id: "",
                goods_name: "",
                remark: "",
                ware_date: this.moment().format('YYYY-MM-DD'),
                apply_id: "",
                dye_factory: "",
                process_factory: "",
            },
            rules: {
                area_id: [
                    {required: true, message: '请选择地区'}
                ],
            },
            applyList: [],
            dyeList: [],
            processList: [],

            houseList: [],
            sampleList: [],
            flowerList: [],
        }
    },
    mounted() {
		this.getApply();
		this.getDye();
		this.getProcess();
    },
    methods: {
        cellStyle(row){
            let cellStyle = '';
            if(row.column.label != '花型' && row.column.label != '备注' && row.column.label != '合计' && row.column.fixed != 'left'){
                cellStyle = {backgroundColor:'#FFF'}
            }else {
                cellStyle = {backgroundColor:'#f4f4f5'}
            }
            return cellStyle
        },
        //显示
        open(mode = 'add') {
            this.mode = mode;
            this.visible = true;
            return this
        },
        //表单提交方法
        submit() {
            let number = 0
            this.form.order_detail.map(item=>{
                number = Number(item.total_number) + number
            })
            this.form.total_num = number
            this.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    this.isSaveing = true;
                    var res = [];
                    if (this.form.id) {
                        res = await this.$API.business.purchase.house.edit.post(this.form);
                    } else {
                        res = await this.$API.business.purchase.house.add.post(this.form);
                    }
                    this.isSaveing = false;
                    if (res.code == 1) {
                        this.visible = false;
                        this.$emit('success', this.form, this.mode)
                        this.$message.success("操作成功")
                    } else {
                        this.$alert(res.message, "提示", {type: 'error'})
                    }
                }
            })
        },
        //表单注入数据
        async setData(data) {
            this.form.id = data.id
            var res = await this.$API.business.purchase.diaobo.detail.get({id: data.id});
            this.form.input_type = res.data.input_type
            this.form.ware_id = Number(res.data.ware_id)
            this.form.dye_id = res.data.dye_id
            this.dye_code = res.data.dye?.purchase_dye_code
            this.form.process_id = res.data.process_id
            this.process_code = res.data.process?.purchase_process_code
            this.form.ware_date = res.data.ware_date
            this.form.goods_id = res.data.goods_id
            this.form.goods_name = res.data.goods_name
            this.form.purchase_ware_code = res.data.purchase_ware_code
            this.form.remark = res.data.remark
            this.form.old_purchase_ware_id = res.data.old_purchase_ware_id
            this.form.total_num = res.data.total_num
            this.form.select_colors = res.data.select_colors
            this.form.select_flower_param = res.data.select_flower_param
            let colorName = []
            res.data.order_detail[0].color_data.map(item=>{
                if(res.data.select_colors.includes(item.color_name)){
                    colorName.push({
                        name: item.color_name,
                        number: item.number
                    })
                }
            })
            this.table_list = colorName
            let array = []
            res.data.order_detail.map(item=>{
                const dynamicFields = Object.fromEntries(
                    this.table_list.map(item1 => {
                        const colorItem = item.color_data.find(c => c.color_name === item1.name);
                        return [item1.name, colorItem?.number || 0];
                    })
                );
                let data = {
                    flower: item.flower,
                    number: item.order_count,
                    remark: item.remark,
                    total_number: item.total_count,
                    ...dynamicFields
                }
                array.push(data)
            })
            this.form.order_detail = array
        },
        // 选择商品
        checkGoods(e){
            this.dialog.goods = true
            this.$nextTick(() => {
                this.$refs.goodsDialog.open('add').setData(e)
            })
        },
        // 选择商品返回
        goodsBack(data){
            this.form.goods_id = data.id
            this.form.goods_name = data.name
        },

        // 选择入库单
        checkArrival(){
            if(!this.form.goods_id){
                this.$message.error('请先选择品名')
                return
            }
            this.dialog.house = true
            this.$nextTick(() => {
                this.$refs.houseDialog.open('add').setData(1,'process')
            })
        },
        // 选择入库单返回
        houseBack(data){
            this.form.buyer_id = data[0].buyer_id
            this.buyer_name = data[0].buyer?.buyer_name
            let array = []
            data.map(item=>{
                array.push({
                    id: item.id,
                    code: item.purchase_ware_code
                })
            })
            this.houseList = array
        },

        // 样本选择
        checkSample(){
            if(!this.form.goods_id) return this.$message.error('请先选择品名')
            this.dialog.sample = true
            this.$nextTick(() => {
                this.$refs.sampleDialog.open('add').setData(1)
            })
        },
        // 样本返回
        sampleBack(data){
            let array = []
            let color = data.colors.split(',')
            color.map(item=>{
                array.push({
                    name: item
                })
            })
            this.sampleList = array
        },

        // 选择花型
        checkFlower(){
            if(!this.form.goods_id) return this.$message.error('请先选择品名')
            this.dialog.flower = true
            this.$nextTick(() => {
                this.$refs.flowerDialog.open('add')
            })
        },
        // 花型返回
        flowerBack(data){
            console.log('data :>> ', data);
            let array = []
            data.map((item,index) =>{
                let exist = this.common.isExist(item.flower_image, this.flowerList, 'flower_image')
                if (exist) {
                    return
                }
                array.push({
                    index: index + 1,
                    flower: item.flower,
                    flower_image: item.flower_image,
                    number: 1
                })
            })
            this.flowerList = [...this.flowerList, ...array]
        },

        // 供应商列表
		async getApply() {
			var res = await this.$API.basic.apply.all.get({type: 1});
			this.applyList = res.data
		},
        // 染色厂列表
		async getDye() {
			var res = await this.$API.basic.apply.all.get({type: 2});
			this.dyeList = res.data
		},
        // 加工厂列表
		async getProcess() {
			var res = await this.$API.basic.apply.all.get({type: 3});
			this.processList = res.data
		},
    }
}
</script>

<style lang="scss" scoped>
:deep(.el-input input[type="number"]::-webkit-outer-spin-button),   
:deep(.el-input input[type="number"]::-webkit-inner-spin-button) {
   -webkit-appearance: none;
   margin: 0;   
}
   
:deep(.el-input input[type="number"]) {
   -moz-appearance: textfield;
}
.inputDeep {
    .el-input__inner {
        cursor: default !important;
        text-align: center;
    }
    :deep(.el-input__wrapper) {
        box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color)) inset;
        height: 20px;
        background: transparent;
        cursor: default;
        .el-input__inner {
            cursor: default !important;
            text-align: center;
        }
    }
}
</style>
